package reflect;

import java.lang.reflect.Field;

/**
 * @author wangyingjie
 * @date
 * @remark 反射操作属性
 */
public class FieldDemo {
    public static class Person{
        private String name;
        private int age;

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

    /**
     * 通过反射设置对象属性
     * @param args
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     * @throws NoSuchMethodException
     */
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException {
        Person person = new Person();
        Class<? extends Person> clazz = person.getClass();
        Field name = clazz.getDeclaredField("name");
        name.setAccessible(true);//设置权限，允许操作private属性
        name.set(person,"小王");
        Field age = clazz.getDeclaredField("age");
        age.setAccessible(true);
        age.set(person,19);
        System.out.println(person);
    }
}
